package com.lp.common.annotation.aspect;

import com.lp.common.annotation.PerCheckAnnotation;
import com.lp.common.context.ContextHolder;
import com.lp.common.context.UserDetail;
import com.lp.common.exception.BaseException;
import com.lp.common.exception.ErrorCodeEnum;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @program: backend
 * @description:
 * @author: Ke.Song
 * @since: 2024-03-12 21:46:34
 */
@Aspect
@Component
public class PerCheckAnnotationAspect {

    @Before("@annotation(perCheckAnnotation)")
    public void beforeMethod(PerCheckAnnotation perCheckAnnotation) {
        Set<String> perList = new HashSet<>(List.of(perCheckAnnotation.value()));
        if (!perList.isEmpty()) {
            UserDetail userDetail = ContextHolder.getContext().getUserDetail();
            Set<String> roles = userDetail.getRoles();
            if (!roles.retainAll(perList)) {
                throw new BaseException(ErrorCodeEnum.AUTHORIZED_FAILED);
            }
        }
    }
}
